package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;

    /**
     * Movement : 动态详情
     * @return
     */
    public String save(Movement movement) {
        //1、保存动态详情数据到 movement表
        mongoTemplate.save(movement);
        //2、保存时间线数据
        timeLineService.saveTimeLine(movement.getUserId(),movement.getId());
        return movement.getId().toHexString();
    }

    //根据用户id查询用户发布的所有动态
    public List<Movement> findByUserId(Integer page, Integer pagesize, Long userId) {
        //1、创建Criteria对象
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("state").is(1);
        //2、创建Query对象，设置分页参数
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        //3、查询
        return mongoTemplate.find(query,Movement.class);
    }

    //根据h好友id查询用户发布的所有动态
    public List<Movement> findByFriendId(Integer page, Integer pagesize, Long friendId) {
        //1、根据好友id，查询时间线表获取数据 List<MovementTimeline>
        Criteria criteria = Criteria.where("friendId").is(friendId);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        List<MovementTimeLine> timeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //2、提取所有的动态id  List<动态id>
        List<ObjectId> movementIds = CollUtil.getFieldValues(timeLines, "movementId", ObjectId.class);
        //3、查询动态向详情数据，根据动态id列表查询数据
        Criteria criteria1 = Criteria.where("id").in(movementIds).and("state").is(1);;
        Query query1 = Query.query(criteria1).with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query1,Movement.class);
    }

    /**
     * mongodb的随机处理
     */
    public List<Movement> randomMovements(Integer pagesize) {
        //1、设置统计方法
        TypedAggregation<Movement> aggregation = TypedAggregation.newAggregation(
                Movement.class,
                Aggregation.sample(pagesize)); //采样
        //2、调用mongoTemplate方法进行数据统计，返回值封装到result对象中
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation,
                Movement.class);
        //3、提取统计结果
        return results.getMappedResults();
    }

    //根据id查询
    public List<Movement> findByIds(Integer page, Integer pagesize, String[] ids) {
        Criteria criteria = Criteria.where("id").in(ids);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize);
        return mongoTemplate.find(query,Movement.class);
    }

    //根据id查询
    public Movement findById(String id) {
        return mongoTemplate.findById(new ObjectId(id),Movement.class);
    }

    //根据动态id，更新状态
    public void updateState(String movementId, Integer state) {
        //update xxx set state = 1 where id = ""
        Query query = Query.query(Criteria.where("id").is(new ObjectId(movementId)));
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }

    /**
     * 查询动态
     * @param page
     * @param pagesize
     * @param userId  有可能为空
     * @param state  有可能为空
     * @return
     */
    public PageResult findAll(Integer page, Integer pagesize, Long userId, Integer state) {
        //1、创建Criteria
        Criteria criteria = new Criteria();
        if(userId != null) {
            criteria.and("userId").is(userId);
        }
        if(state != null) {
            criteria.and("state").is(state);
        }
        //2、创建Query
        Query query = Query.query(criteria);
        //3、查询总数
        long count = mongoTemplate.count(query, Movement.class);
        //4、设置分页参数
        query.with(Sort.by(Sort.Order.desc("created")))
            .limit(pagesize)
            .skip((page-1) * pagesize);
        //5、查询列表
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize, count,list);
    }
}
